package run.bottle.urp.controller;

import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import run.bottle.common.context.ThreadContext;
import run.bottle.common.entity.AppUser;
import run.bottle.common.entity.mvc.RestResponse;
import run.bottle.urp.model.po.Permission;
import run.bottle.urp.model.vo.UserInfoVo;
import run.bottle.urp.service.PermissionService;
import run.bottle.urp.service.RoleService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liyc
 * @date 2022-04-15
 */
@RestController
@RequestMapping("/urp/user")
public class UserController {

    private final PermissionService permissionService;
    private final RoleService roleService;

    public UserController(PermissionService permissionService, RoleService roleService) {
        this.permissionService = permissionService;
        this.roleService = roleService;
    }


    @GetMapping("/current/info")
    public RestResponse getUserInfo() {
        AppUser currentUser = ThreadContext.getCurrentUser();
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(currentUser, userInfoVo);
        userInfoVo.setRole(roleService.findByIdIn(currentUser.getRoleIds()));
        Set<Permission> permissions = new HashSet<>(permissionService.findByRoleIds(currentUser.getRoleIds()));
        userInfoVo.setStringResources(permissions.stream().map(Permission::getResourceKey).collect(Collectors.toSet()));
        permissions = assembleResourceTree(permissions, new HashMap<>());
        userInfoVo.setResources(permissions);
        return RestResponse.ok().result(userInfoVo);
    }

    private Set<Permission> assembleResourceTree(Set<Permission> resourceList, Map<Long, Permission> resourceMap) {
        Set<Permission> menus = new LinkedHashSet<>();
        for (Permission resource : resourceList) {
            resourceMap.put(resource.getId(), resource);
        }
        for (Permission resource : resourceList) {
            Long treePId = resource.getParentId();
            Permission resourceTree = resourceMap.get(treePId);
            if (null != resourceTree && !resource.equals(resourceTree)) {
                Set<Permission> nodes = resourceTree.getChildren();
                if (null == nodes) {
                    nodes = new LinkedHashSet<>();
                    resourceTree.setChildren(nodes);
                }
                nodes.add(resource);
            } else {
                menus.add(resource);
            }
        }
        return menus;
    }


}
